<template>
  <div class="app-container mytree" v-loading="loading">
    <!-- 搜索栏 -->
    <el-row :gutter="20" type="flex">
      <el-col :span="18" :offset="0">
        <el-input
          v-model="filterText"
          placeholder="关键字搜索"
          style="margin-bottom: 20px"
        />
      </el-col>
    </el-row>
    <el-row :gutter="20" 
    >
      <!-- 分类列表区域 -->
      <el-col :span="8" :offset="0">
        <div class="mytree">
          <el-card
            shadow="always"
            :body-style="{ padding: '20px' }"
            class="class-list-card"
          >
            <div slot="header">
              <span>权限列表</span>
            </div>
            <!-- card body -->
            <el-tree
              ref="treeList"
              :data="permissionTree"
              node-key="id"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              class="filter-tree"
              :default-expand-all="true"
              empty-text="权限列表为空，赶紧添加吧"
              @node-click="nodeClick"
            >
              <span class="custom-tree-node" slot-scope="{ node }">
                <span >{{ node.label }}</span>
              </span>
            </el-tree>
          </el-card>
        </div>
      </el-col>
      <!-- 操作区域 -->
      <el-col :span="13" :offset="0">
        <el-card
          shadow="always"
          :body-style="{ padding: '20px' }"
          class="class-form"
        >
          <div slot="header">
            <span>菜单信息</span>
          </div>
           <p v-show="!editAreaFlag"> 请点击权限树 修改关联的角色信息</p>
            <el-form
            ref="form"
            label-width="80px"
            :inline="false"
            size="normal"
            v-show="editAreaFlag"
          >
            <el-form-item label="菜单名称:">
              <el-input v-model="permissonName" :disabled="true"></el-input>
            </el-form-item >
            <el-form-item label="已选角色:">
              <p v-show="userTags.length<1" style="margin:0;">已有员工列表为空，马上去添加添加员工吧！</p>
                <el-tag
                        :key="tag.id"
                        v-for="tag in userTags"
                        closable
                        :disable-transitions="false"
                        @close="delUser(tag)">
                        {{tag}}
                </el-tag>
            </el-form-item >
            <el-form-item label="角色列表:">
              <div class="card-body-scorll">
                <p style="text-align:center;" v-show="userList.length === 0">可选择员工列表为空</p>
                <el-checkbox-group v-model="userTags" @change="handleCheckedUserChange">
                    <el-checkbox  border  v-for="(item) in userList" :key="item.id" :label="item.name" >{{item.name}} </el-checkbox>
                </el-checkbox-group>
            </div>
            </el-form-item >
             <el-form-item >
                <el-button type="primary" size="default" @click="editPermissionRole">保存</el-button>
            </el-form-item >
        </el-form >
           
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {  GetRolesByMenu,GetMenus,GetRoles,ModifyRolesForMenu } from '@/api/accessmanage';

export default {
  data() {
    return {
      filterText:'',
      permissonName:'',
      addEmployeeFlag:true,
      totalCount:null,
      loading:false,
      searchEmployeeName:'',
      addEmployeeLoadingFlag:false,
      loading:false,
      editRoleId:null,
      permissionTree:[],
      editAreaFlag:false,
      defaultPermissionChecked:[],
      userTags:[],
      roleList: [],
      userList:[],
      menuId:null,
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  watch: {
    filterText(val) {
      this.$refs.treeList.filter(val);
    },
  },
  created() {
    this.classListInit();
    this.getRoleLists();
  },
  destroyed(){
  },
  methods: {
   handleCheckedUserChange(val){
      this.userTags = val;
      let that = this;
      let newAry = [];
      this.userTags.forEach(item=>{
        let ary = that.userList.filter(s=>{return s.name === item})[0];
        if(ary){
          newAry.push({
            name:ary.name,
            id:ary.id
          })
        }
      })
      this.roleList = newAry;
        console.log(this.roleList);
    },
    handleCheckAllChange(val){
        this.isIndeterminate = false;
    },
    async editPermissionRole(){
        this.loading = true;
        let ary = [];
        this.roleList.map(item=>{
            ary.push(item.id)
        })
        try {
          let params = {
            menuId:this.menuId,
            roleIds:ary
          }
          console.log(params);
        let res = await ModifyRolesForMenu(params);
        if(res.code === 200){
          this.loading = false;
          console.log(res);
          this.$message.success('绑定角色成功');
        }else{
          this.loading = false;
          // this.defaultPermissionChecked
          this.$message.error('绑定角色失败失败');
        }
      } catch (error) {
        console.log(error);
          this.loading = false;
          this.$message.error('网络请求失败');
      }
    },
    // 获取权限树
    async classListInit(){
        this.loading = true;
        try {
          let res = await GetMenus();
          this.loading = false;
          console.log(res);
          if(res.code === 200){
            this.$message.success('获取权限树成功');
            this.permissionTree = res.data;
          }else{
            this.$message.error('获取权限树失败');
          }
        } catch (error) {
            this.loading = false;
            this.$message.error('网络请求失败');
        }
    },
    async getRoleLists(){
      try {
        let res = await GetRoles();
        if(res.code === 200){
          this.$nextTick(()=>{
              this.userList = res.data;
          })
        }else{
          this.$message.error('获取列表失败')
        }
      } catch (error) {
          this.$message.error('数据请求失败')
      }
    },
    //搜索框关键字搜索
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //职位树默认展开节点获取
    findExpandedNode() { 
     const list = [];
     let _this =this;
     let keysList = [];
     this.treeList.forEach(item =>{
        keysList = keysList.concat(_this.findChildren(item))
     })
     keysList.forEach(element => {
       if (this.$refs.treeList.getNode(element).expanded === true) {
         list.push(element)
       }
     })
     return list
   },

    //成功后执行
    requestSuccessFn(msg){
        this.$set(this.newClass,'label','');
        this.classListInit();
        this.defaultOpenNode = this.findExpandedNode();
        this.loading = false;
        this.$message.success(msg);
    },
    //失败后执行
    requestFailedFn(msg){
        this.loading = false;
        this.$message.error(msg);
    },

    selectChange(item){
      this.selectItem = item;
    },
     removeByValue(arr, attr, value){ 
      var index=0;
      for(var i in arr){
        if(arr[i][attr]==value){
          index=i;
          break;
        }
      }
      arr.splice(index,1);
    },
     delUser(tag){
      this.userTags.splice(this.userTags.indexOf(tag), 1);
       let roleIndex = this.roleList.findIndex(item=>{return item.name === tag});
      this.roleList.splice(roleIndex,1)
      // this.removeByValue(this.roleList,'name',tag);
    },
    //点击职位，展示职位信息
    async nodeClick(data) {
        this.loading = true;
        this.menuId = data.id;
        this.editAreaFlag = true;
        this.permissonName = data.name;
        try {
            let res = await GetRolesByMenu({id:data.id});
            if(res.code === 200){
              this.loading = false;
               let ary = [];
                let aryId = [];
                res.data.forEach(item => {
                  ary.push(item.name);
                  aryId.push({
                    name:item.name,
                    id:item.id
                  })
                });
                this.userTags = ary;
                this.roleList = aryId;
                // this.$message.success('获取节点配置信息成功')
            }else{
              this.loading = false;
                this.$message.error('获取节点配置信息失败，错误信息：'+res.erroMessage)
            }
            
        } catch (error) {
              this.loading = false;
            this.erroMessageShow(error);
        }
    },
    // async popoverShow(){
    //   let res = await getEmployeeList();
    //   this.userList = res;
    // },
  },
};
</script>
<style lang="scss" scope>
@import "~@/styles/mixin.scss";
.el-checkbox.is-bordered+.el-checkbox.is-bordered {
    margin-left: 0px;
}

.el-tag + .el-tag {
    margin-left: 10px;
  }
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.mytree {
  // width: 50%;
  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  .el-tree .el-icon-caret-right:before {
    content: "\e723";
    font-size: 16px;
    color: #1389bc;
  }
  .el-tree .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
    content: "\e722";
    font-size: 16px;
    color: #1389bc;
  }
  .el-tree .el-tree-node__expand-icon.is-leaf.el-icon-caret-right:before {
    content: "\e791";
    color: transparent;
  }
  .class-form,
  .class-list-card {
    min-height: 500px;
    max-height: 500px;
  }
  .filter-tree {
  max-height: 400px;
  overflow: auto;
  @include scrollBar;
}

}

.el-tree-node__content {
  box-sizing: border-box;
  height: 50px;
  width: 100%;
  background-color: #fff;
  border-bottom: 1px solid #f2f2f2;
}
</style>

